import { getMenus, getShops } from "@src/api/catering";
import { storeBindingsBehavior } from "mobx-miniprogram-bindings";
import location from "@src/store/location";
import { getDistance } from "@src/common/utils";
import router from "@src/router";
import cart from "../../store/cart";

Component({
  behaviors: [storeBindingsBehavior],
  storeBindings: [{
    store: cart,
    fields: ['cartList', 'totalFee', 'num'],
    actions: ['initCart'],
  }, {
    store: location,
    fields: ['latitude', 'longitude', 'auth'],
    actions: ['getLocation', 'showAuthTip']
  }],
  data: {
    shopId: null,
    tableNo: null,
    specDialog: null,
    carList: [],
    nodesTop: [],
    currentIndex: 0,
    contentId: '',
    shopInfo: {
      isOpenTime: true
    }
  },
  observers: {
    'shopId': function (shopId) {
      if (shopId) {
        // 初始化对应店铺的购物车
        this.initCart(shopId);
      }
    }
  },
  methods: {
    onLoad(options) {
      let shopId = null;
      let tableNo = null;
      if (options.GLOBAL_SHOP_ID) {
        shopId = options.GLOBAL_SHOP_ID;
      }
      if (options.shopId) {
        shopId = options.shopId;
      }
      if (options.tableNo) {
        tableNo = decodeURIComponent(options.tableNo);
      }
      this.setData({ shopId, tableNo });
    },
    handleSelectSpec(e) {
      this.selectComponent("#spec-dialog").open(e.detail.goods);
    },
    onLogin() {
      this.getLocation().then(res => {
        if (this.data.shopId) {
          this.fetchData();
        } else {
          this.getNearbyShop(res.latitude, res.longitude);
        }
      }).catch(error => {
        this.showAuthTip(error)
        if (this.data.shopId) {
          this.fetchData();
        } else {
          this.getNearbyShop()
        }
      })
    },
    getNearbyShop(latitude, longitude) {
      let data = {}
      if (latitude) {
        data = { latitude, longitude }
      }
      getShops(data).then(res => {
        let shopId = null
        if (res.data.length > 0) {
          for (let i = 0; i < res.data.length; i++) {
            if (shopId) { break; } else {
              if (res.data[i].isOpenTime) {
                shopId = res.data[i].shopId;
                this.setData({
                  shopId: res.data[i].shopId
                })
              }
            }
          }
          this.fetchData();
        } else {
          // 异常处理
          wx.showToast({ title: "尚未配置店铺", icon: "none", duration: 5000 });
        }
      })
    },
    fetchData() {
      let data = { shopId: this.data.shopId }
      getMenus(data).then(res => {
        console.log('点餐getMenus--',res)
        if (res.code !== 0) {
          return;
        }
        let shopInfo = res.data.shopInfo
        let distance = null;
        if (this.data.latitude && shopInfo.latitude) {
          distance = getDistance(this.data.latitude, this.data.longitude, shopInfo.latitude, shopInfo.longitude);
          shopInfo.distance = distance;
        }
        let classifyList = res.data.classifyList;
        let itemMap = res.data.itemMap;
        // 过滤无效分类
        classifyList = classifyList.filter(item => itemMap[item.id] && itemMap[item.id].length > 0)
        this.setData({
          distance: distance,
          shopInfo: shopInfo,
          menuTitle: res.data.menuTitle,
          classifyList: classifyList,
          currentIndex: classifyList.length > 0 ? classifyList[0].id : 0,
          itemMap: itemMap
        })
        this.initCart(data.shopId);
        wx.nextTick(() => {
          this.parseScrollNodes();
        })
      })
    },
    parseScrollNodes() {
      // 解析滚动节点
      wx.createSelectorQuery().selectAll(".classify-title").boundingClientRect(rects => {
        let nodesTop = []
        for (let item of rects) {
          nodesTop.push(item.top - rects[0].top);
        };
        console.log("nodesTop", nodesTop)
        this.setData({ nodesTop: nodesTop })
      }).exec();
    },
    handleGoodsScroll(e) {
      let nodesTop = this.data.nodesTop;
      let top = e.detail.scrollTop;
      if (top < 20) {
      } else if (top > nodesTop[nodesTop.length - 1] - 100) {
      } else {
        for (let e = 0; e < nodesTop.length; e++) {
          if (top <= nodesTop[e + 1] && top >= nodesTop[e]) {
            if (this.data.currentIndex !== this.data.classifyList[e].id)
              this.setData({ currentIndex: this.data.classifyList[e].id })
          }
        }
      }
    },
    handleToChangeShop() {
      router.push({
        name: 'catering/shop',
        params: { shopId: this.data.shopId },
        events: {
          'change': (shopId) => {
            if (shopId !== this.data.shopId) {
              this.setData({ shopId: shopId, tableNo: '' });
              this.fetchData();
            }
          }
        }
      })
    },
    handlePay() {
      router.push({
        name: 'catering/order',
        params: {
          shopId: this.data.shopId,
          tableNo: this.data.tableNo
        },
        success: (res) => {
          console.info('success')
          res.eventChannel.emit('order', {
            shopId: this.data.shopId,
            shopInfo: this.data.shopInfo,
            tableNo: this.data.tableNo,
            cartList: this.data.cartList,
            totalFee: this.data.totalFee,
            num: this.data.num,
          })
        }
      })
    },
    handleCategory(e) {
      let classifyId = e.currentTarget.dataset.id
      this.setData({ contentId: "classify-" + classifyId, currentIndex: classifyId })
    },
  }
})
